define(function(require, exports){
	var pubjs = require('pubjs');
	var grid  = require('@base/highGrid');
	var util = require('util');
	var $ = require('jquery');

	/**
	一些说明
		1. 关于竞价类指标：【竞价请求数，出价数，竞得数，竞得率，使用率】
			- RTB活动：有，但要去掉竞价请求数，因为数量太大，而且意义不大
			- RTB活动/尺寸等：无，后端由于特殊原因统计不到，故要隐藏
			- RTB活动/尺寸等/广告位：有
			- RTB活动/广告位/尺寸等：有
			- 监测活动：无

		2. 指标顺序
			竞得率和竞价请求数要放到前排；metricForward参数

		3. 广告位子表格
			RTB和监测下的广告位子表格是不一样的；'mediaAndAd'和'mediaAndAd_Monitor'参数
	**/



	// condition 数据转换
	// "[{"campaign_id":23},{"spot_size_id":90030}]" --> ["campaign_id", "spot_size_id"]
	function _getCondition(subParam){
		if(util.isString(subParam)){
			subParam = JSON.parse(subParam);
		}

		var data = [];
		for (var i = 0; i < subParam.length; i++) {
			// 每一组condition参数；类型为对象。
			var group = subParam[i];
			// condition_id
			for(var name in group){
				data.push(name);
			}
		}

		return data;
	}

	// 获取子表格配置
	function _getSubgridItems(config){
		var subParam = config.param;

		// 处理 condition 参数
		if(!subParam.condition){
			pubjs.error(LANG('没有condition参数'));
			return false;
		}

		var count = 0;
		var name = _getCondition(subParam.condition);
		var mapping = ['spot_id', 'referer_domain_id', 'channel_id', 'spot_size_id', 'spot_screen_id'];
		for (var i = 0; i < name.length; i++) {
			if(util.find(mapping, name[i]) != null){
				count++;
			}
		}

		// 层层递减到最后一级时，移除 mediaAndAd 这个子项
		// 子表格通用配置项
		// 说明：子表格的项目不一样，少了创意多了创意包，少了活动。
		var subs = [
			'mediaAndAd_Monitor', // 区分RTB和监测
			'sweety',
			'whisky',
			'period',
			'frequency',
			'region',
			'product'
		];

		if(count>=4){
			subs.shift();
		}

		return subs;
	}


	/**	  -----  监测活动/媒体&广告位选项卡 -5个子表格  -----	**/

	// 广告位
	var Spot = grid.base.extend({
		init: function(config){
			config = pubjs.conf(config, {
					url: 'spot/monitorList',
					cols: [
						// {type: 'id'},
						{name:'_id',text:"ID", sort: true,align:'center',width:80}, // @todo 要限制宽度
						{name:'Name',text:LANG("广告位"), type:'index', width: 200, render: 'renderName'},
						{name:'ChannelName',text:LANG("渠道"),align: 'left'},
						{name:'Size',text:LANG("尺寸")},
						{name:'AdvisePrice',text:LANG("参考出价")},
						{name:'Request',text:LANG("竞价请求数")}
					],
					subs: _getSubgridItems(config),
					metrics: ["{front}","{back}","{conversion}","{cost}"], // 监测活动是无竞价组的
					default_metrics : [
						"impressions","new_impressions","old_impressions","visitors","clicks","click_rate","click_reach_rate",
						"back_pageviews",
						"back_regs","back_reg_rate",
						"end_cpc","end_cpm","end_cpa","cost"
					],
					reqType: 'websocket',
					exportParam: 'spot',
					subField: 'spot', // 用于子表格作为父行的标识; 因为gridName:ads已经被主表使用了
					gridName: 'monitorCampaignSpot',
					subFilter: 'subFilter'
				}
			);

			if(util.exist(this.parseSubsCondition(config), 'whisky')){
				util.extend(true, config.get(), {
					'tab':{'bid': null, 'cost': null, 'front': null}
				});
			}

			this.Super('init', arguments);
		},
		subFilter: function(subs, data){
			// 帐号行业类型：1 游戏，有产品版；2 电商，无产品版
			var user = pubjs.getUser();
			var trade = user.current.ExchangeInfo.CategoryId;

			util.each(subs, function(sub){
				// 有产品版的账号才有产品子表格
				if (sub.type === 'product') {
					sub.iconBtn.toggle(trade == 1);
				}
			});
		},
		renderName: function(i, val, data, con){
			var html = $([
				'<div class="text-truncate tl mr10">',
					val,
				'</div>'
			].join('')).attr({
				'title': val
			}).width(180);
			return html;
		}
	});
	exports.spot = Spot;


	// 媒体域名
	var Domain = grid.base.extend({
		init: function(config){
			// 只有当父层有Spot维度时候，才会有竞价类指标

			config = pubjs.conf(config, {
					url: 'domain/list',
					key: 'referer_domain_id',
					param: {
						order: 'impressions|-1'
					},
					cols: [
						{name:'op',text:LANG("操作"), type: 'op'},
						{type: 'id'},
						{name:'referer_domain_name',text:LANG("媒体域名"), type:'index', width: 200, render: 'renderName'}
					],
					default_metrics : [
						"impressions","clicks","click_rate","click_reach_rate",
						"back_pageviews",
						"back_regs","back_reg_rate",
						"end_cpc","end_cpm","end_cpa","cost"
					],
					// 媒体广告位、创意包、落地页、时段、频次、地域、产品
					subs: _getSubgridItems(config),
					metrics: ["{front}","{back}","{conversion}","{cost}"],
					reqType: 'websocket',
					gridName: 'domain',
					subFilter: 'subFilter'
				}
			);

			switch(this.parseSubsCondition(config).pop()){
				case 'campaign':
				case 'package':
				case 'product':
				case 'platform':
					util.extend(true, config.get(), {
						'tab':{'bid': null}
					});
					break;
				case 'product':
					util.extend(true, config.get(), {
						'tab':{'cost': null, 'front': null, 'bid': null}
					});
					break;
			}

			this.Super('init', arguments);
		},
		subFilter: function(subs, data){
			// 帐号行业类型：1 游戏，有产品版；2 电商，无产品版
			var user = pubjs.getUser();
			var trade = user.current.ExchangeInfo.CategoryId;

			util.each(subs, function(sub){
				// 有产品版的账号才有产品子表格
				if (sub.type === 'product') {
					sub.iconBtn.toggle(trade == 1);
				}
			});
		},
		renderName: function(i, val, data, con){
			var html = $([
				'<div class="fl">',
					'<div class="uk-text-truncate">'+data.referer_domain_title+'</div>',
					'<a target="_blank">'+data.referer_domain_name+'</a>',
				'</div>'
			].join(''));
			html.find('a').attr('href', 'http://'+data.referer_domain_name);
			return html.width(con.width-20);
		}
	});
	exports.domain = Domain;

	// 尺寸
	var Size = grid.base.extend({
		init: function(config){
			config = pubjs.conf(config, {
					url: 'spot/size',
					cols: [
						{"type":"id"},
						{name:'Size',text: LANG('广告尺寸'), type:'index', render: 'renderPixelSize', width: 200}
					],
					subFilter: 'subFilter',
					default_metrics : [
						"impressions","clicks","click_rate","click_reach_rate",
						"back_pageviews",
						"back_regs","back_reg_rate",
						"end_cpc","end_cpm","end_cpa","cost"
					],
					subs: _getSubgridItems(config),
					metrics: ["{front}","{back}","{conversion}","{cost}"],
					reqType: 'websocket',
					exportParam: 'spot/size',
					gridName: 'spotSize',
					subFilter: 'subFilter'
				}
			);

			switch(this.parseSubsCondition(config).pop()){
				case 'campaign':
					util.extend(true, config.get(), {
						'tab':{'bid': null}
					});
					break;
				case 'medium':
					util.extend(true, config.get(), {
						'tab':{'bid': null, 'cost': null}
					});
					break;
			}

			this.Super('init', arguments);
		},
		subFilter: function(subs, data){
			// 帐号行业类型：1 游戏，有产品版；2 电商，无产品版
			var user = pubjs.getUser();
			var trade = user.current.ExchangeInfo.CategoryId;

			util.each(subs, function(sub){
				// 有产品版的账号才有产品子表格
				if (sub.type === 'product') {
					sub.iconBtn.toggle(trade == 1);
				}
			});
		},
		renderPixelSize: function(index, value, row, con){
			var text;
			if (!row.Width || !row.Height){
				if(row.Size) {
					text = Math.floor(row.Size/10000) + '*' + (row.Size % 10000);
				}
				else {
					text = '-';
				}
			}else {
				text = row.Width + '*' + row.Height;
			}

			var html = $('<div class="uk-text-truncate fl">'+text+'</div>');
			return html.width(con.width-20);
		}
	});
	exports.size = Size;

	// 屏次
	exports.screens = grid.base.extend({
		init: function(config){
			config = pubjs.conf(config, {
					url: 'spot/screen',
					cols: [
						{"type":"id"},
						{name:'_id',text: LANG('ID'),align:'center',width:80},
						{name:'ScreenName',text: LANG('屏次'), type:'index'}
					],
					default_metrics : [
						"impressions","clicks","click_rate","click_reach_rate",
						"back_pageviews",
						"back_regs","back_reg_rate",
						"end_cpc","end_cpm","end_cpa","cost"
					],
					subs: _getSubgridItems(config),
					metrics: ["{front}","{back}","{conversion}","{cost}"],
					reqType: 'websocket',
					exportParam: 'spot/screen',
					gridName: 'spotScreen',
					subFilter: 'subFilter'
				}
			);

			switch(this.parseSubsCondition(config).pop()){
				case 'medium':
					util.extend(true, config.get(), {
						'tab':{'cost': null}
					});
					break;
			}

			this.Super('init', arguments);
		}
		,subFilter: function(subs, data){
			// 帐号行业类型：1 游戏，有产品版；2 电商，无产品版
			var user = pubjs.getUser();
			var trade = user.current.ExchangeInfo.CategoryId;

			util.each(subs, function(sub){
				// 有产品版的账号才有产品子表格
				if (sub.type === 'product') {
					sub.iconBtn.toggle(trade == 1);
				}
			});
		}
	});

	// 渠道
	exports.channel = grid.base.extend({
		init: function(config){
			config = pubjs.conf(config, {
					url: 'channel/list',
					key: 'channel_id',
					cols: [
						{"type":"id"},
						{name:'channel_id',text: LANG('渠道ID'),align:'center',width:80},
						{name:'channel_name',text: LANG('渠道'), type:'index',align:'left',width:100}
					],
					default_metrics : [
						"impressions","clicks","click_rate","click_reach_rate",
						"back_pageviews",
						"back_regs","back_reg_rate",
						"end_cpc","end_cpm","end_cpa","cost"
					],
					subs: _getSubgridItems(config),
					metrics: ["{front}","{back}","{conversion}","{cost}"],
					reqType: 'websocket',
					exportParam: 'channel',
					gridName: 'spotChannel'
				}
			);

			if(util.exist(this.parseSubsCondition(config), 'whisky')){
				util.extend(true, config.get(), {
					'tab':{'bid': null, 'front': null}
				});
			}

			this.Super('init', arguments);
		}
	});
});